// eslint-disable-next-line
import * as loginService from '@/api/login'
import { notification } from 'ant-design-vue'
import store from '@/store'
import { bxAnaalyse } from '@/core/icons'
// eslint-disable-next-line
import { BasicLayout, BlankLayout, PageView, RouteView } from '@/layouts'

// 前端路由表 (基于动态)
const constantRouterComponents = {
  // 基础页面 layout 必须引入
  BasicLayout: BasicLayout,
  BlankLayout: BlankLayout,
  RouteView: RouteView,
  PageView: PageView
  // '403': () => import(/* webpackChunkName: "error" */ '@/views/exception/403'),
  // '404': () => import(/* webpackChunkName: "error" */ '@/views/exception/404'),
  // '500': () => import(/* webpackChunkName: "error" */ '@/views/exception/500'),

  // 你需要动态引入的页面组件
  // Workplace: () => import('@/views/dashboard/Workplace'),

}

// 前端未找到页面路由（固定不用改）
const notFoundRouter = {
  // path: '*',
  path: '/:pathMatch(.*)*',
  redirect: '/404',
  hidden: true
}
// 按钮操作数组
const permissionBtn = []
// 根级菜单
// const rootRouter = [{
//   // key: '11',
//   // name: 'index',
//   // path: '',
//   // component: 'BasicLayout',
//   // url:'/',
//   // redirect: '/manager/user',
//   // meta: {
//   //   title: '首页'
//   // },

//   children: [],
//   "parentPermissionId": "0",
//   "permissionId": "1",
//   "resourceType": null,
//   "name": "首页",
//   "resourceId": null,
//   "description": "首页",
//   "resourceTypeName": "",
//   "url": "/",
//   "redirect": "/",
//   component: 'BasicLayout'
// }]

/**
 * 动态生成菜单
 * @param token
 * @returns {Promise<Router>}
 */
export const generatorDynamicRouter = token => {
  return new Promise((resolve, reject) => {
    loginService
      .getTree(token)
      .then(res => {
        // 根级菜单
        const rootRouter = [{
          children: [],
          permissionBtn: [],
          'parentPermissionId': '0',
          'permissionId': '1',
          'resourceType': null,
          'name': '首页',
          'resourceId': null,
          'description': '首页',
          'resourceTypeName': '',
          'url': '/',
          'redirect': '/dashboard/workplace',
          component: 'BasicLayout'
        }]
        let result = res.data
        if (JSON.stringify(result) == '[]') {
          notification['error']({
            message: '错误',
            description: '该账户未配置相关权限,请重新登录',
            duration: 4
          })
          setTimeout(() => {
            store.dispatch('Logout').then(() => {
              // _this.$router.push({ name: '/' })
            })
          }, 1500)

          return
        }
        // 获取默认跳转的页面
        // let arrUrl = result.find(item => {
        //   return item.children.length > 0 ? item.children : '/'
        // })
        // if (arrUrl.children.length > 0) {
        //   if (arrUrl.children[0].resourceType == 2) {
        //     rootRouter[0].redirect = arrUrl.children[0].url
        //   } else {
        //     rootRouter[0].redirect = '/'
        //   }
        // } else {
        //   rootRouter[0].redirect = '/'
        // }
        result = ToTree(result)
        rootRouter[0].children = result
        rootRouter[0].permissionBtn = permissionBtn
        const routers = generator(rootRouter)
        // 默认页面
        const item = {
          path: '/dashboard/workplace',
          name: 'Workplace',
          component: () => import('@/views/dashboard/workplace.vue'),
          meta: {
            title: '首页', icon: bxAnaalyse
          }
        }
        routers[0].children.unshift(item)
        routers.push(notFoundRouter)
        resolve(routers)
      })
      .catch(err => {
        reject(err)
      })
  })
}
// /**
//  * 格式化树形结构数据 生成 vue-router 层级路由表
//  *
//  * @param routerMap
//  * @param parent
//  * @returns {*}
//  */
export const generator = (routerMap, parent) => {
  return routerMap.map((item, index) => {
    let currentRouter = {}
    // let url='/'
    // if(item.children.length > 0){
    //   console.log(item.children)
    //   url=item.children[0].url+''
    //   if(url!=null){
    //     url=url.split('/').filter(item => item !== '')[0]
    //   }
    // }

    currentRouter = {
      // 如果路由设置了 path，则作为默认 path，否则 路由地址 动态拼接生成如 /dashboard/workplace
      // path: item.url || (item.children.length > 0 ? item.children[0].url : '/'),
      path: item.url || (item.children.length > 0 ? item.children[0].url + '/index' : '/'),
      // 路由名称，建议唯一
      name: item.name,
      label: item.name,
      title: item.name,
      icon: item.icon,
      value: item.permissionId,
      permissionId: item.permissionId,
      parentPermissionId: item.parentPermissionId,
      key: item.permissionId,
      resourceId: item.resourceId,
      resourceType: item.resourceType,
      resourceTypeName: item.resourceTypeName,
      // 该路由对应页面的 组件 :方案1
      // component: constantRouterComponents[item.component || item.key],
      // 该路由对应页面的 组件 :方案2 (动态加载)
      // component: constantRouterComponents[item.component || item.permissionId ] || (() => import(`@/views/${item.component}`)),
      component: constantRouterComponents[item.component] || (() => import(`@/views${item.url || (item.children.length > 0 ? item.children[0].url : '/')}`)),
      // meta: 页面标题, 菜单图标, 页面权限(供指令权限用，可去掉)
      meta: {
        title: item.name,
        icon: item.icon || undefined,
        // hiddenHeaderContent: undefined,
        // target: undefined,
        permission: item.name
        // hideInBreadcrumb: false
      }
    }
    // 获取权限按钮并赋值
    if (item.permissionId == 1) {
      currentRouter.permissionBtn = item.permissionBtn
    }
    // 为了防止出现后端返回结果不规范，处理有可能出现拼接出两个 反斜杠
    if (!currentRouter.path.startsWith('http')) {
      currentRouter.path = currentRouter.path.replace('//', '/')
    }
    // 重定向
    item.redirect && (currentRouter.redirect = item.redirect)
    // 是否有子菜单，并递归处理
    if (item.children && item.children.length > 0) {
      currentRouter.children = generator(item.children, currentRouter)
    }
    return currentRouter
  })
}

// function getUrl(item) {
//   console.log(item)
//   if (item.url == null || item.url == '') {
//     let childrenUrl = item.children[0].url
//     childrenUrl = childrenUrl.split("/").filter(item => { return item })
//     return  "/" + childrenUrl[0]
//   }
//   else{
//     return item.children[0].url+'/index'
//   }
// }
// 根目录和菜单父级标记
const ToTree = (list) => {
  list.forEach(item => {
    if (item.resourceType == 1) {
      item.component = 'RouteView'
    }
    // 菜单项提取，按钮、接口类型不显示
    if ((item.children.length > 0 && item.resourceType == 1)) {
      ToTree(item.children)
    } else {
      const it = JSON.parse(JSON.stringify(item))
      if (it.resourceType == 2) {
        // 遍历出按钮操作权限
        ToTree(it.children)
      } else {
        if (it.resourceType == 3) {
          if (it.code == null || it.code == '') return
          // 获取按钮操作信息
          permissionBtn.push(it.code)
        }
      }
      item.children = []
    }
  })
  return list
}
